import React, { useState, useEffect } from 'react';
import './home.less';

import { history, useLocation } from 'umi';

import {
  Layout,
  Menu,
  Breadcrumb,
  Dropdown,
  Modal,
  Form,
  Input,
  message,
  Button,
} from 'antd';
import {
  MenuUnfoldOutlined,
  MenuFoldOutlined,
  DownOutlined, //  下拉框
} from '@ant-design/icons';

const { Header, Sider, Content } = Layout;
const { SubMenu } = Menu;

import { firstMenuApi, otherMenuApi } from '@/api/login';

export default function (props) {
  const [state, setState] = useState();
  let location = useLocation();

  const [collapsed, setCollapsed] = useState(false); // 左侧 菜单栏显示 和 隐藏的
  const [firstMenuArr, setFirstMenuArr] = useState([]); // 一级菜单
  const [otherMenuArr, setOtherMenuArr] = useState([]); // 二级菜单
  const [breadTitle, setBreadTitle] = useState('抽奖白名单'); //  面包屑导航

  const [head, setHead] = useState({}); // 页面初始化 获取 用户信息
  const [visible, setVisible] = useState(false); //  头部下拉显示 和 隐藏 按钮

  const [isModalVisible, setIsModalVisible] = useState(false); // 控制弹出框的显示 和 隐藏
  const [showPasswordInfo, setShowPasswordInfo] = useState(''); // 通过字符串 判断显示修改密码 还是  修改 个人信息
  const [form] = Form.useForm(); //  绑定在 表单上的 ref

  const [listenPath, setListenPath] = useState([]); //  监听路由的

  const toggle = () => {
    //  左侧 菜单栏显示 和 隐藏的
    setCollapsed(!collapsed);
  };

  const initMenu = async () => {
    //  初始化  一级 二级菜单接口，获取数据
    let res = await firstMenuApi()
      .then(async (res_1) => {
        // console.log("一级菜单:", res_1.data.data)

        if (res_1.data.code == 200) {
          let parentId = res_1.data.data[0].menuId;
          setFirstMenuArr(res_1.data.data);
          let res_2 = await otherMenuApi({ parentId })
            .then((res_3) => {
              // console.log("二级菜单::", res_3.data.data)

              setOtherMenuArr(res_3.data.data);
            })
            .catch((err_3) => console.log('err_3', err_3));
        }
      })
      .catch((err_1) => console.log('err_1', err_1));
  };

  useEffect(() => {
    let head = JSON.parse(localStorage.getItem('login'));
    // console.log(head)
    setHead(head);
    initMenu();
  }, []);

  useEffect(() => {
    //  监听路由，修改 面包屑导航条
    let path = history.location.pathname.split('/');
    if (path.filter((f) => f === 'addActivity').length > 0) {
      setListenPath(path.filter((f) => f === 'addActivity'));
    } else if (path.filter((f) => f === 'activityDetail').length > 0) {
      setListenPath(path.filter((f) => f === 'activityDetail'));
    } else if (path.filter((f) => f === 'activityComment').length > 0) {
      setListenPath(path.filter((f) => f === 'activityComment'));
    } else {
      setListenPath([]);
    }
  }, [history.location.pathname]);

  const handleMenu = (e) => {
    //  点击 二级菜单，做出相应的 跳转
    let pathname = otherMenuArr.filter((f) => f.menuId == e.key)[0].menuUrl;
    setBreadTitle(otherMenuArr.filter((f) => f.menuId == e.key)[0].menuName);
    history.push({
      pathname: '/home' + pathname,
      // query: {
      //     ...res.data.data
      // }
    });
  };

  const handleMenuClick = ({ key }) => {
    // 点击下拉框中的某一项
    if (key === '1') {
      setShowPasswordInfo('1');
    } else if (key === '2') {
      // localStorage.clear()
      localStorage.removeItem('login');
      history.push({
        pathname: '/login',
      });
      message.success('退出成功!');
    }
  };

  const handleVisibleChange = (flag) => {
    // 鼠标悬浮触发 打开下拉框
    setVisible(flag);
  };

  const handleHead = () => {
    setIsModalVisible(true);
    setShowPasswordInfo('10');
  };

  const showModal = () => {
    //  弹出框 显示
    setIsModalVisible(true);
  };

  const handleOk = () => {
    // 弹出框  确定按钮
    setIsModalVisible(false); // 关闭 弹框
    let { oldPassword, newPassword, againPassword } = form.getFieldsValue(); // 拿到表单里面的内容
    if (showPasswordInfo == '1') {
      // 表示 修改密码 确定事件
      if (newPassword !== againPassword) {
        message.error('两次密码不一致');
      } else if (newPassword && oldPassword && oldPassword) {
        message.success('密码修改成功');
      }

      /**       修改 个人 信息       */
    } else if (showPasswordInfo == '10') {
      console.log('修改  个人 信息');
    }

    // console.log("---", oldPassword, newPassword, againPassword)
    form.resetFields(); //  重置 表单里面的 内容
  };

  const handleCancel = () => {
    //  弹出框   取消按钮
    form.resetFields(); //  重置 表单里面的 内容
    setIsModalVisible(false); //  关闭弹框
  };

  const onFinish = (values) => {
    //  表单验证成功 点击确按钮
    console.log('Success:', values);
  };

  const onFinishFailed = (errorInfo) => {
    // 表单失败，错误信息
    console.log('Failed:', errorInfo);
  };

  const menu = (
    <Menu onClick={handleMenuClick}>
      <Menu.Item key="1" onClick={showModal}>
        修改密码
      </Menu.Item>
      <Menu.Item key="2">退出登录</Menu.Item>
    </Menu>
  );

  return (
    <Layout style={{ minHeight: '100%' }}>
      <Sider trigger={null} collapsible collapsed={collapsed}>
        <div className="layout_title">招行-秦学后台管理</div>
        <Menu
          theme="dark"
          mode="inline"
          defaultSelectedKeys={['1001']}
          onClick={handleMenu}
        >
          {firstMenuArr.length > 0 &&
            firstMenuArr.map((item, index) => {
              return (
                // <Menu.Item key={item.menuId} >
                //   {item.menuName}
                // </Menu.Item>

                <SubMenu key={item.menuId} title={item.menuName}>
                  {otherMenuArr.length > 0 &&
                    otherMenuArr.map((otherItme, otherIndex) => {
                      return (
                        <Menu.Item key={otherItme.menuId}>
                          {' '}
                          {otherItme.menuName}{' '}
                        </Menu.Item>
                      );
                    })}
                </SubMenu>
              );
            })}
        </Menu>
      </Sider>

      <Layout className="site-layout">
        <Header className="site-layout-background" style={{ padding: 0 }}>
          {/* {React.createElement(collapsed ? MenuUnfoldOutlined : MenuFoldOutlined, {
              className: 'trigger',
              onClick: toggle,
            })} */}

          {/* head头部 退出登录选项 */}
          <div className="bread_title">
            <Breadcrumb>
              <Breadcrumb.Item>活动助手</Breadcrumb.Item>
            </Breadcrumb>

            {listenPath[0] == 'activityComment' ? (
              <div>
                <Button
                  onClick={() => {
                    history.push({
                      pathname: '/home/activityComment/basicTree',
                    });
                  }}
                >
                  {' '}
                  时间轴组件{' '}
                </Button>
                <Button
                  onClick={() => {
                    history.push({
                      pathname: '/home/activityComment/item',
                    });
                  }}
                >
                  {' '}
                  树型结构项目{' '}
                </Button>
              </div>
            ) : null}

            <div>
              {Object.values(head).length > 0 && (
                <img
                  style={{
                    width: '35px',
                    height: '35px',
                    borderRadius: '50%',
                    marginRight: '8px',
                    cursor: 'pointer',
                  }}
                  src={head.headPortrait}
                  onClick={handleHead}
                />
              )}

              <Dropdown
                overlay={menu}
                onVisibleChange={handleVisibleChange} // 鼠标悬浮 显示下拉框
                visible={visible}
              >
                <a
                  className="ant-dropdown-link"
                  onClick={(e) => e.preventDefault()}
                  style={{
                    color: '#000',
                  }}
                >
                  {head.userPhone} <DownOutlined />
                </a>
              </Dropdown>
            </div>
          </div>
        </Header>

        <div className="bread_other">
          <Breadcrumb>
            <Breadcrumb.Item>{breadTitle}</Breadcrumb.Item>
            <Breadcrumb.Item>
              {listenPath[0] == 'addActivity'
                ? '添加'
                : listenPath[0] == 'activityDetail'
                ? '详情'
                : null}
            </Breadcrumb.Item>
          </Breadcrumb>
        </div>

        <div className="home_content_all">
          <Content
            className="site-layout-background"
            style={{
              // width: '98%',
              // margin:'0px auto',
              // marginBottom: '20px',
              // padding: 24,
              borderRadius: '15px',
              height: '100%',
            }}
          >
            {props.children}
          </Content>
        </div>
      </Layout>

      {/* 弹出框的 显示 和 隐藏 */}
      <Modal
        title={showPasswordInfo == '1' ? '修改密码' : '个人中心'}
        visible={isModalVisible}
        getContainer={false} //  解决 Form.useForm() 的一个警告，这个弹出框问题还是解决不了
        onOk={handleOk}
        onCancel={handleCancel}
      >
        {showPasswordInfo == '1' ? (
          <div>
            <Form
              name="basic"
              form={form}
              // labelCol={{ span: 8 }}
              // wrapperCol={{ span: 16 }}
              initialValues={{
                oldPassword: '',
                newPassword: '',
                againPassword: '',
              }}
              // onFinish={handleOk}
              // onFinishFailed={onFinishFailed}
              autoComplete="off"
            >
              <Form.Item
                label="旧密码"
                name="oldPassword"
                rules={[{ required: true, message: '请输入旧密码!' }]}
              >
                <Input.Password />
              </Form.Item>

              <Form.Item
                label="新密码"
                name="newPassword"
                rules={[{ required: true, message: '请输入新密码!' }]}
                hasFeedback
              >
                <Input.Password />
              </Form.Item>

              <Form.Item
                label="确认密码"
                name="againPassword"
                dependencies={['newPassword']}
                hasFeedback
                rules={[
                  { required: true, message: '请再次确认密码!' },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (!value || getFieldValue('newPassword') === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(
                        new Error('您输入的两个密码不匹配!'),
                      );
                    },
                  }),
                ]}
              >
                <Input.Password />
              </Form.Item>
              {/* 
                  <Form.Item name="remember" valuePropName="checked" wrapperCol={{ offset: 8, span: 16 }}>
                    <Checkbox>Remember me</Checkbox>
                  </Form.Item> */}

              {/* <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                    <Button type="primary" htmlType="submit">
                      Submit
                    </Button>
                  </Form.Item> */}
            </Form>
          </div>
        ) : (
          <div className="head_userInfo">
            <div className="userInfo_item">
              <div>头像:</div>
              <div>
                <img
                  style={{
                    width: '35px',
                    height: '35px',
                    borderRadius: '50%',
                    cursor: 'pointer',
                  }}
                  src={head.headPortrait}
                />
                <span
                  style={{ fontSize: '12px', color: '#ccc', cursor: 'pointer' }}
                >
                  {' '}
                  点击修改头像{' '}
                </span>
              </div>
            </div>

            <div className="userInfo_item">
              <div> 账号: </div>
              <div> {head.userAccount} </div>
            </div>

            <div className="userInfo_item">
              <div> 姓名: </div>
              <div> {head.userName} </div>
            </div>

            <div className="userInfo_item">
              <div> 手机号: </div>
              <div> {head.userPhone} </div>
            </div>

            <div className="userInfo_item">
              <div> 性别: </div>
              <div> 不详 </div>
            </div>
          </div>
        )}
      </Modal>
    </Layout>

    // <div
    //   style={{
    //     height: '100vh',
    //   }}
    // >
    //   <ProLayout
    //     menuItemRender={(item, dom) => <div>{dom}</div>}
    //     subMenuItemRender={(_, dom) => <div>{dom}</div>}
    //     title="招行-秦学后台管理"
    //     menuHeaderRender={(logo, title) => (
    //       <div
    //         // id="customize_menu_header"
    //         // onClick={() => {
    //           // console.log("---", title)
    //         // }}
    //       >
    //         {title}
    //       </div>
    //     )}

    //     {...defaultProps}
    //     location={{
    //       pathname: '/welcome',
    //     }}

    //     onTopMixMenuHeaderClick={() => {
    //       console.log("点击")
    //     }}
    //   >
    //     <PageContainer content="创建活动">Hello World</PageContainer>
    //   </ProLayout>
    // </div>
  );
}
